//登录注册模块仓库

import { reqGetCode, reqUserRegister, reqUserLogin, reqGetUserInfo, reqLogout } from "@/api"
import { setToken, getToken, removeToken } from "@/utils/token"

const state = {
    code:'',
    token: getToken(),
    userInfo:{}
}
const actions = {
    //获取验证码
    async getCode({ commit }, phone) {
        let res = await reqGetCode(phone)
        // console.log(res);
        //正常情况下验证码是发到用户的手机上，不需要我们手动填写
        if(res.code == 200) {
            commit('GETCODE', res.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //用户注册
    async userRegister({ commit }, user) {
        let res = await reqUserRegister(user)
        // console.log(res);
        if (res.code == 200) {
            return "ok";
        } else {
            return Promise.reject(new Error("faile"))
        }
    },
    //用户登录
    async userLogin({commit}, data) {
        let res = await reqUserLogin(data)
        // console.log(res);
        if(res.code == 200) {
            commit('USERLOGIN', res.data.token)
            //将token存储到本地
            setToken(res.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error("faile"))
        }
    },
    //获取用户信息
    async getUserInfo({commit}) {
        let res = await reqGetUserInfo()
        // console.log(res);
        if(res.code == 200) {
            commit('GETUSERINFO', res.data)
            return 'ok'
        } else {
            return Promise.reject(new Error("faile"))
        }
    },
    //退出登录
    async userLogout({commit}) {
        let res = await reqLogout()
        console.log(res);
        if(res.code == 200) {
            commit('CLEARUSERINFO')
            return 'ok'
        } else {
            return Promise.reject(new Error("faile"))
        }
    }
}
const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    CLEARUSERINFO(state) {
        state.token = ''
        state.userInfo = {}
        removeToken()
    }
}
const getters = {}

export default {
    state,
    actions,
    mutations,
    getters
}